package MyThread;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-16
 * Time: 10:17
 */

/**
 * 造成线程安全原因之三：内存可见性
 */
public class Demo {

    private static int flag = 0;
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{

            while (flag == 0){      //编译器操作系统层面，会有读内存操作和读寄存器操作，后续load从寄存器读取
                                    //后续t2线程用户输入，改变flag值，t1线程已经感觉不到了(没有读取真正的内存)
            }
        });

        Thread t2 = new Thread(()->{

            Scanner in = new Scanner(System.in);
            System.out.println("请输入 flag");
            flag = in.nextInt();
        });

        t1.start();
        t2.start();
    }
}
